package com.xca.znb.view;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.GridView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import com.bumptech.glide.Glide;
import com.xca.znb.R;
import com.xca.znb.entity.Collect;
import com.xca.znb.entity.Trends;
import com.xca.znb.entity.User;
import com.xca.znb.model.impl.MyFriendsImpl;
import com.xca.znb.presenter.MyFriendsPresenter;

import org.json.JSONArray;
import org.json.JSONException;

import java.util.ArrayList;
import java.util.List;

public class MyFriendsPublish extends AppCompatActivity {
    private ListView listView ;
    private ImageView backBtn ;
    private ArrayAdapter<Trends> adapter ;
    private List<Trends> trendsList ;
    private ArrayAdapter<String> adapterImg ;
    private MyFriendsPresenter presenter ;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.my_friends_publish);
        listView = findViewById(R.id.my_friends_list);
        backBtn = findViewById(R.id.my_friends_back);

        MyFriendsImpl myFriendsImpl = new MyFriendsImpl(this);
        presenter = new MyFriendsPresenter(myFriendsImpl);

        backBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });
    }

    private void trendsAdapter(){

        adapter = new ArrayAdapter<Trends>(this, R.layout.my_friends_circle_item ,R.id.mf_show_phone ,trendsList){
            ArrayList<String> imgList = new ArrayList<>();
            public View getView(int position , View converView , ViewGroup parent){
                View view = super.getView(position, converView, parent);
                ImageView userImg = view.findViewById(R.id.mf_show_avatar);
                TextView userName = view.findViewById(R.id.mf_show_phone);
                TextView userPhone = view.findViewById(R.id.my_show_publish_time);
                ImageButton delFriends = view.findViewById(R.id.mf_del);
                TextView text = view.findViewById(R.id.mf_show_publish_text);
                GridView images = view.findViewById(R.id.mf_show_publish_img);

                Trends trends = getItem(position);
                if (trends != null){
                    String uerPhone = trends.getPublisher();
                    User user = presenter.getUserByPhone(uerPhone);
                    if (user != null){
                        Glide.with(MyFriendsPublish.this)
                                .load(user.getConcern())
                                .into(userImg);
                        if (user.getName()==null){
                            userName.setText(trends.getPublisher());
                        }else {
                            userName.setText(user.getName());
                            userPhone.setText(trends.getPublisher());
                        }
                    }

                    text.setText(trends.getText());

                    imgList.clear();
                    String jsonImgPath = trends.getImg_list();
                    String[] imgPath = convertJsonToArray(jsonImgPath);
                    for (String img : imgPath){
                        imgList.add(img);
                    }
                    imgItemAdapter();
                    images.setAdapter(adapterImg);
                    adapter.notifyDataSetChanged();

                    delFriends.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            int id = trends.getId();
                            new AlertDialog.Builder(MyFriendsPublish.this)
                                    .setMessage("确定删除该动态吗？")
                                    .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {
                                            presenter.deleteTrendsById(id);
                                            Toast.makeText(MyFriendsPublish.this, "删除成功", Toast.LENGTH_SHORT).show();
                                            getTrendsList();
                                        }
                                    })
                                    .setNegativeButton("取消",null)
                                    .create().show();
                        }
                    });
                }

                return view ;
            }
            void imgItemAdapter(){
                adapterImg = new ArrayAdapter<String>(MyFriendsPublish.this, R.layout.friends_img_item , R.id.friends_circle_text_item , imgList){
                    public View getView(int position , View converView , ViewGroup parents){
                        View view = super.getView(position, converView, parents);
                        TextView showText = view.findViewById(R.id.friends_circle_text_item);
                        ImageView showImg = view.findViewById(R.id.friends_circle_img_item);
                        String imgPath = imgList.get(position);
                        Bitmap bitmap = stringPathToBitmap(imgPath);
                        if (bitmap != null){
                            showImg.setImageBitmap(bitmap);
                        }
                        return view ;
                    }
                };
            }
        };
    }

    public Bitmap stringPathToBitmap(String imagePath) {
        try {
            // 使用BitmapFactory.decodeFile方法将图片路径转换为Bitmap对象
            Bitmap bitmap = BitmapFactory.decodeFile(imagePath);

            if (bitmap != null) {
                return bitmap;
            } else {
                // 图片加载失败处理
                // Log.e("ImageLoadError", "Failed to load image from path: " + imagePath);
                return null;
            }
        } catch (Exception e) {
            e.printStackTrace();
            // 异常处理
            return null;
        }
    }

    private static  String[] convertJsonToArray(String jsonString){
        String[] imgPathArray = null ;
        try {
            JSONArray jsonArray = new JSONArray(jsonString);
            imgPathArray = new String[jsonArray.length()] ;
            for (int i = 0 ; i < jsonArray.length() ; i++){
                imgPathArray[i] = jsonArray.getString(i) ;
            }
        } catch (JSONException e) {
            throw new RuntimeException(e);
        }
        return imgPathArray ;
    }

    private void getTrendsList(){
        SharedPreferences sharedPreferences = getSharedPreferences("loginPhone", Context.MODE_PRIVATE);
        String phone = sharedPreferences.getString("phone" , "");
        trendsList = presenter.getTrendsByUser(phone);
        trendsAdapter();
        listView.setAdapter(adapter);
        adapter.notifyDataSetChanged();
    }

    @Override
    protected void onResume() {
        super.onResume();
        getTrendsList();
    }
}